﻿using Lhz.Sc.Entity.Database;
using Lhz.Sc.Entity.Enum;
using System;
using System.Linq;

namespace Lhz.Sc.Business
{
    public static class OperationQueryableExpansion
    {
        public static IQueryable<Operation> QueryByServiceGuid(this IQueryable<Operation> query, Guid? serviceGuid)
        {
            if (serviceGuid.HasValue)
            {
                query = query.Where(r => r.ServiceGuid == serviceGuid);
            }
            return query;
        }

        public static IQueryable<Operation> QueryByUserGuid(this IQueryable<Operation> query, Guid? userGuid)
        {
            if (userGuid.HasValue)
            {
                var authorizations = new AuthorizationProxy().QueryByUserGuid(userGuid.Value);
                var applicationGuids = authorizations.Where(r => r.AuthorizationType == AuthorizationType.ApplicationAuthorization).Select(r => r.ObjectGuid);
                var serviceGuids = authorizations.Where(r => r.AuthorizationType == AuthorizationType.ServiceAuthorization).Select(r => r.ObjectGuid);
                var operationGuids = authorizations.Where(r => r.AuthorizationType == AuthorizationType.OperationAuthorization).Select(r => r.ObjectGuid);
                query = query.Where(r => applicationGuids.Contains(r.Service.ApplicationGuid) || serviceGuids.Contains(r.ServiceGuid) || operationGuids.Contains(r.Guid));
            }
            return query;
        }
    }
}
